
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>中间件 &#8212; Django 3.2.6.dev 文档</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="next" title="迁移操作" href="migration-operations.html" />
    <link rel="prev" title="表单和字段验证" href="forms/validation.html" />



 
<script src="../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 3.2.6.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="forms/validation.html" title="表单和字段验证">previous</a>
     |
    <a href="index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="migration-operations.html" title="迁移操作">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-middleware">
            
  <div class="section" id="s-module-django.middleware">
<span id="s-middleware"></span><span id="module-django.middleware"></span><span id="middleware"></span><h1>中间件<a class="headerlink" href="#module-django.middleware" title="永久链接至标题">¶</a></h1>
<p>这篇文档解释了所有 Django 自带的中间件组件。关于如何使用它们以及如何编写自己的中间件，请参见 <a class="reference internal" href="../topics/http/middleware.html"><span class="doc">中间件使用指南</span></a>。</p>
<div class="section" id="s-available-middleware">
<span id="available-middleware"></span><h2>可用的中间件<a class="headerlink" href="#available-middleware" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-module-django.middleware.cache">
<span id="s-cache-middleware"></span><span id="module-django.middleware.cache"></span><span id="cache-middleware"></span><h3>缓存中间件<a class="headerlink" href="#module-django.middleware.cache" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.middleware.cache.UpdateCacheMiddleware">
<em class="property">class </em><code class="descname">UpdateCacheMiddleware</code><a class="headerlink" href="#django.middleware.cache.UpdateCacheMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<dl class="class">
<dt id="django.middleware.cache.FetchFromCacheMiddleware">
<em class="property">class </em><code class="descname">FetchFromCacheMiddleware</code><a class="headerlink" href="#django.middleware.cache.FetchFromCacheMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>启用全站缓存。如果启用了这些功能，那么每一个 Django 驱动的页面都会在 <a class="reference internal" href="settings.html#std:setting-CACHE_MIDDLEWARE_SECONDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></code></a> 配置定义的时间内被缓存。参见 <a class="reference internal" href="../topics/cache.html"><span class="doc">缓存文档</span></a>。</p>
</div>
<div class="section" id="s-module-django.middleware.common">
<span id="s-common-middleware"></span><span id="module-django.middleware.common"></span><span id="common-middleware"></span><h3>“通用”中间件<a class="headerlink" href="#module-django.middleware.common" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.middleware.common.CommonMiddleware">
<em class="property">class </em><code class="descname">CommonMiddleware</code><a class="headerlink" href="#django.middleware.common.CommonMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>为完美主义者增加了一些便利：</p>
<ul>
<li><p class="first">禁止 <a class="reference internal" href="settings.html#std:setting-DISALLOWED_USER_AGENTS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DISALLOWED_USER_AGENTS</span></code></a> 配置中的用户代理访问，它应该是一个编译的正则表达式对象列表。</p>
</li>
<li><p class="first">根据 <a class="reference internal" href="settings.html#std:setting-APPEND_SLASH"><code class="xref std std-setting docutils literal notranslate"><span class="pre">APPEND_SLASH</span></code></a> 和 <a class="reference internal" href="settings.html#std:setting-PREPEND_WWW"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PREPEND_WWW</span></code></a> 的配置进行 URL 重写。</p>
<p>如果 <a class="reference internal" href="settings.html#std:setting-APPEND_SLASH"><code class="xref std std-setting docutils literal notranslate"><span class="pre">APPEND_SLASH</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，并且初始的 URL 没有以斜线结尾，而且在 URLconf 中也没有找到，那么就会在最后附加一个斜线形成一个新的 URL。如果在 URLconf 中找到了这个新的 URL，那么 Django 会将请求重定向到这个新的 URL。否则，初始的 URL 就会被照常处理。</p>
<p>例如，<code class="docutils literal notranslate"><span class="pre">foo.com/bar</span></code> 将被重定向到 <code class="docutils literal notranslate"><span class="pre">foo.com/bar/</span></code>，如果你没有 <code class="docutils literal notranslate"><span class="pre">foo.com/bar</span></code> 的有效 URL 模式，但 <em>有</em> <code class="docutils literal notranslate"><span class="pre">foo.com/bar/</span></code> 的有效模式。</p>
<p>如果 <a class="reference internal" href="settings.html#std:setting-PREPEND_WWW"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PREPEND_WWW</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，缺乏前导“www. ”的 URL 将被重定向到带有前导“www. ”的同一 URL。</p>
<p>这两个选项都是为了规范 URL。其理念是，每个 URL 应该存在于一个地方，而且只有一个地方。从技术上讲，URL <code class="docutils literal notranslate"><span class="pre">foo.com/bar</span></code> 与 <code class="docutils literal notranslate"><span class="pre">foo.com/bar/</span></code> 是不同的——搜索引擎索引器会将它们视为单独的 URL——所以最好的做法是将 URL 规范化。</p>
<p>If necessary, individual views may be excluded from the <code class="docutils literal notranslate"><span class="pre">APPEND_SLASH</span></code>
behavior using the <a class="reference internal" href="../topics/http/decorators.html#django.views.decorators.common.no_append_slash" title="django.views.decorators.common.no_append_slash"><code class="xref py py-func docutils literal notranslate"><span class="pre">no_append_slash()</span></code></a>
decorator:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.common</span> <span class="kn">import</span> <span class="n">no_append_slash</span>

<span class="nd">@no_append_slash</span>
<span class="k">def</span> <span class="nf">sensitive_fbv</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;View to be excluded from APPEND_SLASH.&quot;&quot;&quot;</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">()</span>
</pre></div>
</div>
<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p>Support for the <a class="reference internal" href="../topics/http/decorators.html#django.views.decorators.common.no_append_slash" title="django.views.decorators.common.no_append_slash"><code class="xref py py-func docutils literal notranslate"><span class="pre">no_append_slash()</span></code></a>
decorator was added.</p>
</div>
</li>
<li><p class="first">设置非流响应的 <code class="docutils literal notranslate"><span class="pre">Content-Length</span></code> 头。</p>
</li>
</ul>
<dl class="attribute">
<dt id="django.middleware.common.CommonMiddleware.response_redirect_class">
<code class="descclassname">CommonMiddleware.</code><code class="descname">response_redirect_class</code><a class="headerlink" href="#django.middleware.common.CommonMiddleware.response_redirect_class" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>默认为 <a class="reference internal" href="request-response.html#django.http.HttpResponsePermanentRedirect" title="django.http.HttpResponsePermanentRedirect"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponsePermanentRedirect</span></code></a>。子类化 <code class="docutils literal notranslate"><span class="pre">CommonMiddleware</span></code>，并重写该属性来定制中间件发出的重定向。</p>
<dl class="class">
<dt id="django.middleware.common.BrokenLinkEmailsMiddleware">
<em class="property">class </em><code class="descname">BrokenLinkEmailsMiddleware</code><a class="headerlink" href="#django.middleware.common.BrokenLinkEmailsMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<ul class="simple">
<li>向 <code class="xref std std-setting docutils literal notranslate"><span class="pre">manager</span></code> 发送失效链接通知邮件（参见 <a class="reference internal" href="../howto/error-reporting.html"><span class="doc">发送错误</span></a>）。</li>
</ul>
</div>
<div class="section" id="s-module-django.middleware.gzip">
<span id="s-gzip-middleware"></span><span id="module-django.middleware.gzip"></span><span id="gzip-middleware"></span><h3>GZip 中间件<a class="headerlink" href="#module-django.middleware.gzip" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.middleware.gzip.GZipMiddleware">
<em class="property">class </em><code class="descname">GZipMiddleware</code><a class="headerlink" href="#django.middleware.gzip.GZipMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p class="last">安全研究人员最近发现，当在网站上使用压缩技术（包括 <code class="docutils literal notranslate"><span class="pre">GZipMiddleware</span></code>）时，网站可能会受到一些可能的攻击。在你的网站上使用 <code class="docutils literal notranslate"><span class="pre">GZipMiddleware</span></code> 之前，你应该仔细考虑你是否会受到这些攻击。如果你对你是否受到影响有 <em>任何</em> 怀疑，你应该避免使用 <code class="docutils literal notranslate"><span class="pre">GZipMiddleware</span></code>。更多细节，请看 <a class="reference external" href="http://breachattack.com/resources/BREACH%20-%20SSL,%20gone%20in%2030%20seconds.pdf">the BREACH paper (PDF)</a> 和 <a class="reference external" href="http://breachattack.com">breachattack.com</a> 。</p>
</div>
<p><code class="docutils literal notranslate"><span class="pre">django.middleware.gzip.GZipMiddleware</span></code> 为能理解 GZip 压缩的浏览器（所有现代浏览器）压缩内容。</p>
<p>这个中间件应该放在任何其他需要读取或写入响应体的中间件之前，这样压缩就会在之后发生。</p>
<p>如果以下任何一项为真，它将不会压缩内容：</p>
<ul class="simple">
<li>内容主体长度小于 200 字节。</li>
<li>响应已经设置了 <code class="docutils literal notranslate"><span class="pre">Content-Encoding</span></code> 头。</li>
<li>请求（浏览器）没有发送包含 <code class="docutils literal notranslate"><span class="pre">gzip</span></code> 的 <code class="docutils literal notranslate"><span class="pre">Accept-Encoding</span></code> 头。</li>
</ul>
<p>如果响应有 <code class="docutils literal notranslate"><span class="pre">ETag</span></code> 头，则 ETag 会变得很弱，以符合 <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7232.html#section-2.1"><strong>RFC 7232#section-2.1</strong></a>。</p>
<p>你可以使用 <a class="reference internal" href="../topics/http/decorators.html#django.views.decorators.gzip.gzip_page" title="django.views.decorators.gzip.gzip_page"><code class="xref py py-func docutils literal notranslate"><span class="pre">gzip_page()</span></code></a> 装饰器对单个视图应用 GZip 压缩。</p>
</div>
<div class="section" id="s-module-django.middleware.http">
<span id="s-conditional-get-middleware"></span><span id="module-django.middleware.http"></span><span id="conditional-get-middleware"></span><h3>条件 GET 中间件<a class="headerlink" href="#module-django.middleware.http" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.middleware.http.ConditionalGetMiddleware">
<em class="property">class </em><code class="descname">ConditionalGetMiddleware</code><a class="headerlink" href="#django.middleware.http.ConditionalGetMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>处理有条件的 GET 操作。如果响应没有 <code class="docutils literal notranslate"><span class="pre">ETag</span></code> 头，中间件会根据需要添加一个。如果响应有 <code class="docutils literal notranslate"><span class="pre">ETag</span></code> 或 <code class="docutils literal notranslate"><span class="pre">Last-Modified</span></code> 头，而请求有 <code class="docutils literal notranslate"><span class="pre">If-None-Match</span></code> 或 <code class="docutils literal notranslate"><span class="pre">If-Modified-Since</span></code>，则响应被一个 <a class="reference internal" href="request-response.html#django.http.HttpResponseNotModified" title="django.http.HttpResponseNotModified"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponseNotModified</span></code></a> 替换。</p>
</div>
<div class="section" id="s-module-django.middleware.locale">
<span id="s-locale-middleware"></span><span id="module-django.middleware.locale"></span><span id="locale-middleware"></span><h3>本地化中间件<a class="headerlink" href="#module-django.middleware.locale" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.middleware.locale.LocaleMiddleware">
<em class="property">class </em><code class="descname">LocaleMiddleware</code><a class="headerlink" href="#django.middleware.locale.LocaleMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>可以根据请求的数据选择语言。它为每个用户定制内容。请参阅 <a class="reference internal" href="../topics/i18n/translation.html"><span class="doc">国际化文档</span></a>。</p>
<dl class="attribute">
<dt id="django.middleware.locale.LocaleMiddleware.response_redirect_class">
<code class="descclassname">LocaleMiddleware.</code><code class="descname">response_redirect_class</code><a class="headerlink" href="#django.middleware.locale.LocaleMiddleware.response_redirect_class" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>默认为 <a class="reference internal" href="request-response.html#django.http.HttpResponseRedirect" title="django.http.HttpResponseRedirect"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponseRedirect</span></code></a>。子类化 <code class="docutils literal notranslate"><span class="pre">LocaleMiddleware</span></code> 并重写该属性，以自定义中间件发出的重定向。</p>
</div>
<div class="section" id="s-module-django.contrib.messages.middleware">
<span id="s-message-middleware"></span><span id="module-django.contrib.messages.middleware"></span><span id="message-middleware"></span><h3>消息中间件<a class="headerlink" href="#module-django.contrib.messages.middleware" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.contrib.messages.middleware.MessageMiddleware">
<em class="property">class </em><code class="descname">MessageMiddleware</code><a class="headerlink" href="#django.contrib.messages.middleware.MessageMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>启用基于 cookie 和会话的消息支持。参见 <a class="reference internal" href="contrib/messages.html"><span class="doc">消息文档</span></a>。</p>
</div>
<div class="section" id="s-module-django.middleware.security">
<span id="s-id1"></span><span id="s-security-middleware"></span><span id="module-django.middleware.security"></span><span id="id1"></span><span id="security-middleware"></span><h3>安全中间件<a class="headerlink" href="#module-django.middleware.security" title="永久链接至标题">¶</a></h3>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p class="last">如果你的部署情况允许，通常让你的前端 Web 服务器执行“安全中间件”提供的功能是个好主意。这样一来，如果有一些请求不是由 Django 服务的（比如静态资源或用户上传的文件），它们将和对你的 Django 应用的请求有同样的保护。</p>
</div>
<dl class="class">
<dt id="django.middleware.security.SecurityMiddleware">
<em class="property">class </em><code class="descname">SecurityMiddleware</code><a class="headerlink" href="#django.middleware.security.SecurityMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">django.middleware.security.SecurityMiddleware</span></code> 为请求／响应周期提供了若干安全增强功能。每一项都可以通过设置独立地启用或禁用。</p>
<ul class="simple">
<li><a class="reference internal" href="settings.html#std:setting-SECURE_BROWSER_XSS_FILTER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_BROWSER_XSS_FILTER</span></code></a></li>
<li><a class="reference internal" href="settings.html#std:setting-SECURE_CONTENT_TYPE_NOSNIFF"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_CONTENT_TYPE_NOSNIFF</span></code></a></li>
<li><a class="reference internal" href="settings.html#std:setting-SECURE_HSTS_INCLUDE_SUBDOMAINS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_HSTS_INCLUDE_SUBDOMAINS</span></code></a></li>
<li><a class="reference internal" href="settings.html#std:setting-SECURE_HSTS_PRELOAD"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_HSTS_PRELOAD</span></code></a></li>
<li><a class="reference internal" href="settings.html#std:setting-SECURE_HSTS_SECONDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_HSTS_SECONDS</span></code></a></li>
<li><a class="reference internal" href="settings.html#std:setting-SECURE_REDIRECT_EXEMPT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_REDIRECT_EXEMPT</span></code></a></li>
<li><a class="reference internal" href="settings.html#std:setting-SECURE_REFERRER_POLICY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_REFERRER_POLICY</span></code></a></li>
<li><a class="reference internal" href="settings.html#std:setting-SECURE_SSL_HOST"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_SSL_HOST</span></code></a></li>
<li><a class="reference internal" href="settings.html#std:setting-SECURE_SSL_REDIRECT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_SSL_REDIRECT</span></code></a></li>
</ul>
<div class="section" id="s-http-strict-transport-security">
<span id="s-id2"></span><span id="http-strict-transport-security"></span><span id="id2"></span><h4>HTTP 严格传输安全<a class="headerlink" href="#http-strict-transport-security" title="永久链接至标题">¶</a></h4>
<p>对于只能通过 HTTPS 访问的网站，你可以通过设置 <a class="reference external" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security">&quot;Strict-Transport-Security&quot; 头</a> 来指示现代浏览器拒绝通过不安全的连接连接到你的域名（在给定的时间内）。这可以减少你受到一些 SSL 剥离中间人（MITM）的攻击。</p>
<p>如果你将 <a class="reference internal" href="settings.html#std:setting-SECURE_HSTS_SECONDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_HSTS_SECONDS</span></code></a> 设置为一个非零的整数值，<code class="docutils literal notranslate"><span class="pre">SecurityMiddleware</span></code> 将为你在所有 HTTPS 响应中设置这个头。</p>
<p>当启用 HSTS 时，最好先使用一个小值进行测试，例如 <a class="reference internal" href="settings.html#std:setting-SECURE_HSTS_SECONDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_HSTS_SECONDS=3600</span></code></a> 为一小时。每次 Web 浏览器看到你的网站的 HSTS 头时，它将在给定的时间内拒绝与你的域名进行非安全通信（使用 HTTP）。一旦你确认你的网站上所有的资产都是安全服务的（即 HSTS 没有破坏任何东西），最好是增加这个值，这样不经常访问的人就会受到保护（31536000秒，即 1 年，是常见的）。</p>
<p>此外，如果你将 <a class="reference internal" href="settings.html#std:setting-SECURE_HSTS_INCLUDE_SUBDOMAINS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_HSTS_INCLUDE_SUBDOMAINS</span></code></a> 设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，<code class="docutils literal notranslate"><span class="pre">SecurityMiddleware</span></code> 将在 <code class="docutils literal notranslate"><span class="pre">Strict-Transport-Security</span></code> 头中添加 <code class="docutils literal notranslate"><span class="pre">includeSubDomains</span></code> 指令。建议这样做（假设所有的子域都只使用 HTTPS 服务），否则你的网站仍然可能通过不安全的连接到子域而受到攻击。</p>
<p>如果你希望将你的网站提交到 <a class="reference external" href="https://hstspreload.org/">浏览器预加载列表</a> ，请将 <a class="reference internal" href="settings.html#std:setting-SECURE_HSTS_PRELOAD"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_HSTS_PRELOAD</span></code></a> 设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code>。这样就会把 <code class="docutils literal notranslate"><span class="pre">preload</span></code> 指令附加到 <code class="docutils literal notranslate"><span class="pre">Strict-Transport-Security</span></code> 头。</p>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p>HSTS 策略适用于你的整个域，而不仅仅是你设置响应头的 URL。因此，你应该只在你的整个域名只通过 HTTPS 服务时使用它。</p>
<p class="last">适当尊重 HSTS 头的浏览器将拒绝允许用户绕过警告，并连接到使用过期、自签名或其他无效 SSL 证书的网站。如果你使用 HSTS，请确保你的证书处于良好状态，并保持这种状态！</p>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">如果你部署在负载平衡器或反向代理服务器后面，而 <code class="docutils literal notranslate"><span class="pre">Strict-Transport-Security</span></code> 头没有被添加到你的响应中，这可能是因为 Django 没有意识到它是在一个安全的连接上；你可能需要设置 <a class="reference internal" href="settings.html#std:setting-SECURE_PROXY_SSL_HEADER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_PROXY_SSL_HEADER</span></code></a> 设置。</p>
</div>
</div>
<div class="section" id="s-referrer-policy">
<span id="s-id4"></span><span id="referrer-policy"></span><span id="id4"></span><h4>Referrer 政策<a class="headerlink" href="#referrer-policy" title="永久链接至标题">¶</a></h4>
<p>浏览器使用 <a class="reference external" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer">referer 头</a> 作为向网站发送关于用户如何到达那里的信息的一种方式。当用户点击一个链接时，浏览器将发送链接页面的完整 URL 作为 referrer。虽然这对某些目的来说可能很有用——例如查明谁在链接到你的网站——但它也可能引起隐私问题，因为它告诉一个网站，一个用户正在访问另一个网站。</p>
<p>一些浏览器能够接受关于是否应该在用户点击链接时发送 HTTP <code class="docutils literal notranslate"><span class="pre">Referer</span></code> 头的提示；这种提示通过 <a class="reference external" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy">Referrer-Policy 头</a> 提供。这个头可以向浏览器建议三种行为中的任何一种：</p>
<ul class="simple">
<li>完整 URL：在 <code class="docutils literal notranslate"><span class="pre">Referer</span></code> 头中发送整个URL。例如，如果用户访问 <code class="docutils literal notranslate"><span class="pre">https://example.com/page.html</span></code>，<code class="docutils literal notranslate"><span class="pre">Referer</span></code> 头将包含 <code class="docutils literal notranslate"><span class="pre">&quot;https://example.com/page.html&quot;</span></code>。</li>
<li>仅起源：只发送 referrer 中的“起源”。起源由方案、主机和（可选）端口号组成。例如，如果用户访问的是 <code class="docutils literal notranslate"><span class="pre">https://example.com/page.html</span></code>，起源就是 <code class="docutils literal notranslate"><span class="pre">https://example.com/</span></code>。</li>
<li>无 referrer：完全不发送 <code class="docutils literal notranslate"><span class="pre">Referer</span></code> 头。</li>
</ul>
<p>有两种类型的情况，这个头可以告诉浏览器要注意：</p>
<ul class="simple">
<li>同源与跨源：从 <code class="docutils literal notranslate"><span class="pre">https://example.com/1.html</span></code> 到 <code class="docutils literal notranslate"><span class="pre">https://example.com/2.html</span></code> 的链接为同源链接。从 <code class="docutils literal notranslate"><span class="pre">https://example.com/page.html</span></code> 到 <code class="docutils literal notranslate"><span class="pre">https://not.example.com/page.html</span></code> 的链接为跨源链接。</li>
<li>协议降级：如果包含链接的页面是通过 HTTPS 服务的，但被链接的页面不是通过 HTTPS 服务的，就会发生降级。</li>
</ul>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p class="last">当你的网站通过 HTTPS 提供服务时， <a class="reference internal" href="csrf.html#using-csrf"><span class="std std-ref">Django 的 CSRF 保护系统</span></a> 需要 <code class="docutils literal notranslate"><span class="pre">Referer</span></code> 头存在，所以完全禁用 <code class="docutils literal notranslate"><span class="pre">Referer</span></code> 头会干扰 CSRF 保护。要想在保留 CSRF 保护的同时，获得禁用 <code class="docutils literal notranslate"><span class="pre">Referer</span></code> 头的大部分好处，可以考虑只启用同源引用。</p>
</div>
<p><code class="docutils literal notranslate"><span class="pre">SecurityMiddleware</span></code> 可以根据 <a class="reference internal" href="settings.html#std:setting-SECURE_REFERRER_POLICY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_REFERRER_POLICY</span></code></a> 设置，为你设置 <code class="docutils literal notranslate"><span class="pre">Referrer-Policy</span></code> 头（注意拼写：当用户点击链接时，浏览器会发送一个 <code class="docutils literal notranslate"><span class="pre">Referer</span></code> 头，但指示浏览器是否这样做的头是拼写为 <code class="docutils literal notranslate"><span class="pre">Referrer-Policy</span></code>）。该设置的有效值为：</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">no-referrer</span></code></dt>
<dd>指示浏览器对在本网站上点击的链接不发送 referrer。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">no-referrer-when-downgrade</span></code></dt>
<dd>指示浏览器发送完整的 URL 作为 referrer，但只有在没有发生协议降级的情况下。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">origin</span></code></dt>
<dd>指示浏览器只发送起源，而不是完整的 URL 作为 referrer。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">origin-when-cross-origin</span></code></dt>
<dd>指示浏览器发送完整的 URL 作为同源链接的 referrer，而只发送起源给跨源链接。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">same-origin</span></code></dt>
<dd>指示浏览器发送完整的 URL，但只针对同源链接。对于跨源链接，将不发送 referrer。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">strict-origin</span></code></dt>
<dd>指示浏览器只发送起源，而不是完整的 URL，并在协议降级时不发送 referrer。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">strict-origin-when-cross-origin</span></code></dt>
<dd>当链接为同源且不发生协议降级时，指示浏览器发送完整的 URL；当链接为跨源且不发生协议降级时，只发送起源；当发生协议降级时，不发送 referrer。</dd>
<dt><code class="docutils literal notranslate"><span class="pre">unsafe-url</span></code></dt>
<dd>指示浏览器始终发送完整的 URL 作为 referrer。</dd>
</dl>
<div class="admonition-unknown-policy-values admonition">
<p class="first admonition-title">未知政策值</p>
<p class="last">当一个策略值被用户代理认为 <a class="reference external" href="https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values">未知</a> 时，可以指定多个策略值以提供后备。最后一个被理解的指定值优先。为了支持这一点，可以在 <a class="reference internal" href="settings.html#std:setting-SECURE_REFERRER_POLICY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_REFERRER_POLICY</span></code></a> 中使用一个可迭代对象或逗号分隔的字符串。</p>
</div>
</div>
<div class="section" id="s-x-content-type-options-nosniff">
<span id="s-x-content-type-options"></span><span id="x-content-type-options-nosniff"></span><span id="x-content-type-options"></span><h4><code class="docutils literal notranslate"><span class="pre">X-Content-Type-Options:</span> <span class="pre">nosniff</span></code><a class="headerlink" href="#x-content-type-options-nosniff" title="永久链接至标题">¶</a></h4>
<p>一些浏览器会试图猜测它们获取的资源的内容类型，覆盖 <code class="docutils literal notranslate"><span class="pre">Content-Type</span></code> 头。虽然这可以帮助显示配置不当的服务器的网站，但也会带来安全风险。</p>
<p>如果你的网站提供用户上传的文件，恶意用户可能会上传一个特制的文件，当你认为它是无害的东西时，该文件会被浏览器解释为 HTML 或 JavaScript。</p>
<p>为了防止浏览器猜测内容类型，并迫使它总是使用 <code class="docutils literal notranslate"><span class="pre">Content-Type</span></code> 头中提供的类型，你可以传递 <a class="reference external" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options">X-Content-Type-Options: nosniff</a> 头。 如果 <a class="reference internal" href="settings.html#std:setting-SECURE_CONTENT_TYPE_NOSNIFF"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_CONTENT_TYPE_NOSNIFF</span></code></a> 设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，<code class="docutils literal notranslate"><span class="pre">SecurityMiddleware</span></code> 将对所有的响应进行这样的操作。</p>
<p>需要注意的是，在大多数部署情况下，Django 并不参与服务用户上传的文件，这个设置对你没有帮助。例如，如果你的 <a class="reference internal" href="settings.html#std:setting-MEDIA_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_URL</span></code></a> 是由你的前端 Web 服务器（nginx，Apache等）直接提供服务的，那么你会希望在那里设置这个头。另一方面，如果你使用 Django 来做一些事情，比如需要授权才能下载文件，而你又不能用你的 Web 服务器来设置头，那么这个设置就会很有用。</p>
</div>
<div class="section" id="s-x-xss-protection-1-mode-block">
<span id="s-x-xss-protection"></span><span id="x-xss-protection-1-mode-block"></span><span id="x-xss-protection"></span><h4><code class="docutils literal notranslate"><span class="pre">X-XSS-Protection:</span> <span class="pre">1;</span> <span class="pre">mode=block</span></code><a class="headerlink" href="#x-xss-protection-1-mode-block" title="永久链接至标题">¶</a></h4>
<p>一些浏览器有能力阻止看起来是 <a class="reference external" href="https://en.wikipedia.org/wiki/Cross-site_scripting">XSS 攻击</a> 的内容。它们的工作原理是在页面的 GET 或 POST 参数中寻找 JavaScript 内容。如果 JavaScript 在服务器的响应中被重放，页面就会被阻止渲染，并显示一个错误页面。</p>
<p><a class="reference external" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection">X-XSS-Protection 头</a> 用于控制 XSS 过滤器的操作。</p>
<p>要在浏览器中启用 XSS 过滤器，并强制其始终阻止可疑的 XSS 攻击，你可以通过 <code class="docutils literal notranslate"><span class="pre">X-XSS-Protection:</span> <span class="pre">1;</span> <span class="pre">mode=block</span></code> 头。如果 <a class="reference internal" href="settings.html#std:setting-SECURE_BROWSER_XSS_FILTER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_BROWSER_XSS_FILTER</span></code></a> 设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，<code class="docutils literal notranslate"><span class="pre">SecurityMiddleware</span></code> 将对所有响应进行此操作。</p>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p class="last">浏览器 XSS 过滤器是一种有用的防御措施，但不能完全依赖它。它不能检测所有的 XSS 攻击，而且不是所有的浏览器都支持头。确保你仍然 <a class="reference internal" href="../topics/security.html#cross-site-scripting"><span class="std std-ref">验证和消毒</span></a> 所有输入，以防止 XSS 攻击。</p>
</div>
</div>
<div class="section" id="s-ssl-redirect">
<span id="s-id10"></span><span id="ssl-redirect"></span><span id="id10"></span><h4>SSL 重定向<a class="headerlink" href="#ssl-redirect" title="永久链接至标题">¶</a></h4>
<p>如果你的网站同时提供 HTTP 和 HTTPS 连接，大多数用户最终会默认使用不安全的连接。为了达到最佳的安全性，你应该将所有的 HTTP 连接重定向到 HTTPS。</p>
<p>如果你将 <a class="reference internal" href="settings.html#std:setting-SECURE_SSL_REDIRECT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_SSL_REDIRECT</span></code></a> 设置为 True，<code class="docutils literal notranslate"><span class="pre">SecurityMiddleware</span></code> 将永久（HTTP 301）重定向所有 HTTP 连接到 HTTPS。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">出于性能方面的考虑，最好在 Django 之外，在前端负载均衡器或反向代理服务器（如 <a class="reference external" href="https://nginx.org/">nginx</a> ）中做这些重定向。 <a class="reference internal" href="settings.html#std:setting-SECURE_SSL_REDIRECT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_SSL_REDIRECT</span></code></a> 是为了在部署情况下，这不是一个选项。</p>
</div>
<p>如果 <a class="reference internal" href="settings.html#std:setting-SECURE_SSL_HOST"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_SSL_HOST</span></code></a> 设置有一个值，所有的重定向将被发送到该主机，而不是最初要求的主机。</p>
<p>如果你的网站上有几个页面应该通过 HTTP 提供，而不是重定向到 HTTPS，你可以在 <a class="reference internal" href="settings.html#std:setting-SECURE_REDIRECT_EXEMPT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_REDIRECT_EXEMPT</span></code></a> 设置中列出正则表达式来匹配这些 URL。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">如果你部署在负载均衡器或反向代理服务器后面，而 Django 似乎无法判断一个请求是否真的已经安全，你可能需要设置 <a class="reference internal" href="settings.html#std:setting-SECURE_PROXY_SSL_HEADER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_PROXY_SSL_HEADER</span></code></a> 配置。</p>
</div>
</div>
</div>
<div class="section" id="s-module-django.contrib.sessions.middleware">
<span id="s-session-middleware"></span><span id="module-django.contrib.sessions.middleware"></span><span id="session-middleware"></span><h3>会话中间件<a class="headerlink" href="#module-django.contrib.sessions.middleware" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.contrib.sessions.middleware.SessionMiddleware">
<em class="property">class </em><code class="descname">SessionMiddleware</code><a class="headerlink" href="#django.contrib.sessions.middleware.SessionMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>启用会话支持。参见 <a class="reference internal" href="../topics/http/sessions.html"><span class="doc">会话文档</span></a>。</p>
</div>
<div class="section" id="s-module-django.contrib.sites.middleware">
<span id="s-site-middleware"></span><span id="module-django.contrib.sites.middleware"></span><span id="site-middleware"></span><h3>站点中间件<a class="headerlink" href="#module-django.contrib.sites.middleware" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.contrib.sites.middleware.CurrentSiteMiddleware">
<em class="property">class </em><code class="descname">CurrentSiteMiddleware</code><a class="headerlink" href="#django.contrib.sites.middleware.CurrentSiteMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>将代表当前站点的 <code class="docutils literal notranslate"><span class="pre">site</span></code> 属性添加到每个传入的 <code class="docutils literal notranslate"><span class="pre">HttpRequest</span></code> 对象中。参见 <a class="reference internal" href="contrib/sites.html#site-middleware"><span class="std std-ref">站点文档</span></a>。</p>
</div>
<div class="section" id="s-module-django.contrib.auth.middleware">
<span id="s-authentication-middleware"></span><span id="module-django.contrib.auth.middleware"></span><span id="authentication-middleware"></span><h3>验证中间件<a class="headerlink" href="#module-django.contrib.auth.middleware" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.contrib.auth.middleware.AuthenticationMiddleware">
<em class="property">class </em><code class="descname">AuthenticationMiddleware</code><a class="headerlink" href="#django.contrib.auth.middleware.AuthenticationMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>将代表当前登录的用户的 <code class="docutils literal notranslate"><span class="pre">user</span></code> 属性添加到每个传入的 <code class="docutils literal notranslate"><span class="pre">HttpRequest</span></code> 对象中。见 <a class="reference internal" href="../topics/auth/default.html#auth-web-requests"><span class="std std-ref">Web 请求中的验证</span></a>。</p>
<dl class="class">
<dt id="django.contrib.auth.middleware.RemoteUserMiddleware">
<em class="property">class </em><code class="descname">RemoteUserMiddleware</code><a class="headerlink" href="#django.contrib.auth.middleware.RemoteUserMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>用于利用 Web 服务器提供的认证的中间件。详细使用方法请看 <a class="reference internal" href="../howto/auth-remote-user.html"><span class="doc">使用 REMOTE_USER 进行身份验证</span></a>。</p>
<dl class="class">
<dt id="django.contrib.auth.middleware.PersistentRemoteUserMiddleware">
<em class="property">class </em><code class="descname">PersistentRemoteUserMiddleware</code><a class="headerlink" href="#django.contrib.auth.middleware.PersistentRemoteUserMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>当仅在登录页面启用时，利用 Web 服务器提供的认证的中间件。详细使用方法参见 <a class="reference internal" href="../howto/auth-remote-user.html#persistent-remote-user-middleware-howto"><span class="std std-ref">仅在登录界面使用 REMOTE_USER</span></a>。</p>
</div>
<div class="section" id="s-csrf-protection-middleware">
<span id="csrf-protection-middleware"></span><h3>CSRF 保护中间件<a class="headerlink" href="#csrf-protection-middleware" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.middleware.csrf.CsrfViewMiddleware">
<em class="property">class </em><code class="descname">CsrfViewMiddleware</code><a class="headerlink" href="#django.middleware.csrf.CsrfViewMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>通过在 POST 表单中添加隐藏的表单字段，并检查请求的正确值，增加对跨站点伪造请求的保护。请参阅 <a class="reference internal" href="csrf.html"><span class="doc">跨站点伪造请求保护文档</span></a>。</p>
</div>
<div class="section" id="s-x-frame-options-middleware">
<span id="x-frame-options-middleware"></span><h3><code class="docutils literal notranslate"><span class="pre">X-Frame-Options</span></code> 中间件<a class="headerlink" href="#x-frame-options-middleware" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.middleware.clickjacking.XFrameOptionsMiddleware">
<em class="property">class </em><code class="descname">XFrameOptionsMiddleware</code><a class="headerlink" href="#django.middleware.clickjacking.XFrameOptionsMiddleware" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>简单的 <a class="reference internal" href="clickjacking.html"><span class="doc">通过 X-Frame-Options 头的点击劫持保护</span></a>。</p>
</div>
</div>
<div class="section" id="s-middleware-ordering">
<span id="s-id11"></span><span id="middleware-ordering"></span><span id="id11"></span><h2>中间件顺序<a class="headerlink" href="#middleware-ordering" title="永久链接至标题">¶</a></h2>
<p>下面是关于各种 Django 中间件类的排序的一些提示：</p>
<ol class="arabic">
<li><p class="first"><a class="reference internal" href="#django.middleware.security.SecurityMiddleware" title="django.middleware.security.SecurityMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">SecurityMiddleware</span></code></a></p>
<p>如果你要开启 SSL 重定向，它应该排在列表的最前面，因为这样可以避免运行一堆其他不必要的中间件。</p>
</li>
<li><p class="first"><a class="reference internal" href="#django.middleware.cache.UpdateCacheMiddleware" title="django.middleware.cache.UpdateCacheMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">UpdateCacheMiddleware</span></code></a></p>
<p>在修改 <code class="docutils literal notranslate"><span class="pre">Vary</span></code> 头（<code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code>、<code class="docutils literal notranslate"><span class="pre">GZipMiddleware</span></code>、<code class="docutils literal notranslate"><span class="pre">LocaleMiddleware</span></code>）之前。</p>
</li>
<li><p class="first"><a class="reference internal" href="#django.middleware.gzip.GZipMiddleware" title="django.middleware.gzip.GZipMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">GZipMiddleware</span></code></a></p>
<p>在任何可能改变或使用响应体的中间件之前。</p>
<p>在 <code class="docutils literal notranslate"><span class="pre">UpdateCacheMiddleware</span></code> 之后：修改 <code class="docutils literal notranslate"><span class="pre">Vary</span></code> 头。</p>
</li>
<li><p class="first"><a class="reference internal" href="#django.contrib.sessions.middleware.SessionMiddleware" title="django.contrib.sessions.middleware.SessionMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">SessionMiddleware</span></code></a></p>
<p>在任何可能引发异常触发错误视图的中间件之前（如 <a class="reference internal" href="exceptions.html#django.core.exceptions.PermissionDenied" title="django.core.exceptions.PermissionDenied"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PermissionDenied</span></code></a>），如果你使用的是 <a class="reference internal" href="settings.html#std:setting-CSRF_USE_SESSIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_USE_SESSIONS</span></code></a>。</p>
<p>在 <code class="docutils literal notranslate"><span class="pre">UpdateCacheMiddleware</span></code> 之后：修改 <code class="docutils literal notranslate"><span class="pre">Vary</span></code> 头。</p>
</li>
<li><p class="first"><a class="reference internal" href="#django.middleware.http.ConditionalGetMiddleware" title="django.middleware.http.ConditionalGetMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConditionalGetMiddleware</span></code></a></p>
<p>在任何可能改变响应的中间件之前（它设置 <code class="docutils literal notranslate"><span class="pre">ETag</span></code> 头）。</p>
<p>在 <code class="docutils literal notranslate"><span class="pre">GZipMiddleware</span></code> 之后，这样它就不会在 gzip 压缩后的内容上计算 <code class="docutils literal notranslate"><span class="pre">ETag</span></code> 头。</p>
</li>
<li><p class="first"><a class="reference internal" href="#django.middleware.locale.LocaleMiddleware" title="django.middleware.locale.LocaleMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">LocaleMiddleware</span></code></a></p>
<p>最上面的一个，仅次于 <code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code> （使用会话数据）和 <code class="docutils literal notranslate"><span class="pre">UpdateCacheMiddleware</span></code> （修改 <code class="docutils literal notranslate"><span class="pre">Vary</span></code> 头）。</p>
</li>
<li><p class="first"><a class="reference internal" href="#django.middleware.common.CommonMiddleware" title="django.middleware.common.CommonMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">CommonMiddleware</span></code></a></p>
<p>在任何可能改变响应的中间件之前（它设置 <code class="docutils literal notranslate"><span class="pre">Content-Length</span></code> 头）。出现在 <code class="docutils literal notranslate"><span class="pre">CommonMiddleware</span></code> 之前并改变响应的中间件必须重置 <code class="docutils literal notranslate"><span class="pre">Content-Length</span></code>。</p>
<p>靠近顶部：当 <a class="reference internal" href="settings.html#std:setting-APPEND_SLASH"><code class="xref std std-setting docutils literal notranslate"><span class="pre">APPEND_SLASH</span></code></a> 或 <a class="reference internal" href="settings.html#std:setting-PREPEND_WWW"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PREPEND_WWW</span></code></a> 设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code> 时，它会重定向。</p>
<p>在 <code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code> 之后，如果你使用 <a class="reference internal" href="settings.html#std:setting-CSRF_USE_SESSIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_USE_SESSIONS</span></code></a>。</p>
</li>
<li><p class="first"><a class="reference internal" href="#django.middleware.csrf.CsrfViewMiddleware" title="django.middleware.csrf.CsrfViewMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">CsrfViewMiddleware</span></code></a></p>
<p>在任何假设 CSRF 攻击已经被处理的视图中间件之前。</p>
<p>在 <a class="reference internal" href="#django.contrib.auth.middleware.RemoteUserMiddleware" title="django.contrib.auth.middleware.RemoteUserMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">RemoteUserMiddleware</span></code></a>，或任何其他可能执行登录的认证中间件，从而旋转 CSRF 令牌，然后再向下调用中间件链。</p>
<p>在 <code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code> 之后，如果你使用 <a class="reference internal" href="settings.html#std:setting-CSRF_USE_SESSIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_USE_SESSIONS</span></code></a>。</p>
</li>
<li><p class="first"><a class="reference internal" href="#django.contrib.auth.middleware.AuthenticationMiddleware" title="django.contrib.auth.middleware.AuthenticationMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">AuthenticationMiddleware</span></code></a></p>
<p><code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code> 之后：使用会话存储。</p>
</li>
<li><p class="first"><a class="reference internal" href="#django.contrib.messages.middleware.MessageMiddleware" title="django.contrib.messages.middleware.MessageMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">MessageMiddleware</span></code></a></p>
<p><code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code> 之后：可以使用基于会话的存储。</p>
</li>
<li><p class="first"><a class="reference internal" href="#django.middleware.cache.FetchFromCacheMiddleware" title="django.middleware.cache.FetchFromCacheMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">FetchFromCacheMiddleware</span></code></a></p>
<p>在任何修改 <code class="docutils literal notranslate"><span class="pre">Vary</span></code> 头的中间件之后：该头用于为缓存哈希键选取一个值。</p>
</li>
<li><p class="first"><a class="reference internal" href="contrib/flatpages.html#django.contrib.flatpages.middleware.FlatpageFallbackMiddleware" title="django.contrib.flatpages.middleware.FlatpageFallbackMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">FlatpageFallbackMiddleware</span></code></a></p>
<p>应该是接近底部，因为这是一种最后的中间件。</p>
</li>
<li><p class="first"><a class="reference internal" href="contrib/redirects.html#django.contrib.redirects.middleware.RedirectFallbackMiddleware" title="django.contrib.redirects.middleware.RedirectFallbackMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">RedirectFallbackMiddleware</span></code></a></p>
<p>应该是接近底部，因为这是一种最后的中间件。</p>
</li>
</ol>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">中间件</a><ul>
<li><a class="reference internal" href="#available-middleware">可用的中间件</a><ul>
<li><a class="reference internal" href="#module-django.middleware.cache">缓存中间件</a></li>
<li><a class="reference internal" href="#module-django.middleware.common">“通用”中间件</a></li>
<li><a class="reference internal" href="#module-django.middleware.gzip">GZip 中间件</a></li>
<li><a class="reference internal" href="#module-django.middleware.http">条件 GET 中间件</a></li>
<li><a class="reference internal" href="#module-django.middleware.locale">本地化中间件</a></li>
<li><a class="reference internal" href="#module-django.contrib.messages.middleware">消息中间件</a></li>
<li><a class="reference internal" href="#module-django.middleware.security">安全中间件</a><ul>
<li><a class="reference internal" href="#http-strict-transport-security">HTTP 严格传输安全</a></li>
<li><a class="reference internal" href="#referrer-policy">Referrer 政策</a></li>
<li><a class="reference internal" href="#x-content-type-options-nosniff"><code class="docutils literal notranslate"><span class="pre">X-Content-Type-Options:</span> <span class="pre">nosniff</span></code></a></li>
<li><a class="reference internal" href="#x-xss-protection-1-mode-block"><code class="docutils literal notranslate"><span class="pre">X-XSS-Protection:</span> <span class="pre">1;</span> <span class="pre">mode=block</span></code></a></li>
<li><a class="reference internal" href="#ssl-redirect">SSL 重定向</a></li>
</ul>
</li>
<li><a class="reference internal" href="#module-django.contrib.sessions.middleware">会话中间件</a></li>
<li><a class="reference internal" href="#module-django.contrib.sites.middleware">站点中间件</a></li>
<li><a class="reference internal" href="#module-django.contrib.auth.middleware">验证中间件</a></li>
<li><a class="reference internal" href="#csrf-protection-middleware">CSRF 保护中间件</a></li>
<li><a class="reference internal" href="#x-frame-options-middleware"><code class="docutils literal notranslate"><span class="pre">X-Frame-Options</span></code> 中间件</a></li>
</ul>
</li>
<li><a class="reference internal" href="#middleware-ordering">中间件顺序</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="forms/validation.html"
                        title="上一章">表单和字段验证</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="migration-operations.html"
                        title="下一章">迁移操作</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/ref/middleware.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">7月 23, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="forms/validation.html" title="表单和字段验证">previous</a>
     |
    <a href="index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="migration-operations.html" title="迁移操作">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>